<?php

/**
 */

namespace App\Api\CatchOrder;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use \GuzzleHttp\Client;

class DouYinLaiKe
{
    protected $client;
    protected $baseUrl;
    protected $cookie;
    public function __construct()
    {
        $this->client = new Client();
        $this->baseUrl = 'https://life.douyin.com';
        //---------------------------需要做处理---------------------------
        // $this->cookie = 's_v_web_id=verify_lf7v5vrp_h2kcXzVh_NWYE_4NkZ_BX87_GsKVMiSXtVQx; csrf_session_id=dea15ba75af8d538c52f2cb1f87497e6; passport_csrf_token=587a83f4a794ebc68e7c588b82b88a65; passport_csrf_token_default=587a83f4a794ebc68e7c588b82b88a65; store-region=cn-ha; store-region-src=uid; __live_version__="1.1.0.7556"; live_can_add_dy_2_desktop="1"; msToken=mcQuhXkJyWbvR0GQSSxnHIMfq_fxZcQBU8QtvIaINuu-RGkoUAFXZgnRJjN-tudbZcpGcZnJycdb4p6eJdgr55fFbpvKEkwh5-2s8vDhqj3jeun3cMvd; odin_tt=a96a320ffb9d932dd47e005e75cea33ad0be556705ecbe8e86ea0a3630c131bf97d62882099fd8c913215d4f121dbf334926a0471518e3e23fc498c75a023c38; passport_auth_status_ls=c1c9b20d0698ef5d83ebbcdaf133af68,6ba29b430a3661f4814b2e50b175448d; passport_auth_status_ss_ls=c1c9b20d0698ef5d83ebbcdaf133af68,6ba29b430a3661f4814b2e50b175448d; sid_guard_ls=328cf907e1bfb8132bf3213322e9ede6|1678784767|5184000|Sat,+13-May-2023+09:06:07+GMT; uid_tt_ls=cfb36aac12b03f4403700de1cb5f55d6; uid_tt_ss_ls=4717f2828456dcbbfd5f4350ea935b1c; sid_tt_ls=328cf907e1bfb8132bf3213322e9ede6; sessionid_ls=328cf907e1bfb8132bf3213322e9ede6; sessionid_ss_ls=328cf907e1bfb8132bf3213322e9ede6; sid_ucp_v1_ls=1.0.0-KGVmNzYxNDYxNTllZTRjMjU1N2EzYjBkZjY0ZDMxOGM2ZTJmYmNjMzgKGgidgNCXi42LBxD_8cCgBhjRwRIgDDgCQPEHGgJobCIgMzI4Y2Y5MDdlMWJmYjgxMzJiZjMyMTMzMjJlOWVkZTY; ssid_ucp_v1_ls=1.0.0-KGVmNzYxNDYxNTllZTRjMjU1N2EzYjBkZjY0ZDMxOGM2ZTJmYmNjMzgKGgidgNCXi42LBxD_8cCgBhjRwRIgDDgCQPEHGgJobCIgMzI4Y2Y5MDdlMWJmYjgxMzJiZjMyMTMzMjJlOWVkZTY; ttwid=1|waMr5fo25nsVGxJqcmJyDld54gfxVGG_limETfxKgwY|1678789256|a6b000db4ff400b07dcd81c5a9c67d1607226fd6b05d78a12e178042c2ce7d93';
        $this->cookie = 's_v_web_id=verify_lhq2b2c0_V0zJe18O_unIu_4ZJ5_9qHH_1pbfChquCD9l;store-region-src=uid;msToken=nfo9iY0nX-NiGNgizYH3Ujs6i8ufVfVVStM2j7z-KsrnZZMSG-vfh5t4RlSynCoDxW2Fl35Htr7gauEYo42O1cEWKgvIWjTM_SrxXjrZmFbzlg2yGDy4;passport_auth_status_ls=ef7fb704c1b7d5df9d983d33cb6cdbe8,;passport_auth_status_ss_ls=ef7fb704c1b7d5df9d983d33cb6cdbe8,;sid_guard_ls=ed77ed518a76f1cec49d0006a541a971|1684228774|5184001|Sat,+15-Jul-2023+09:19:35+GMT;sessionid_ss_ls=ed77ed518a76f1cec49d0006a541a971;sessionid_ls=ed77ed518a76f1cec49d0006a541a971;sid_tt_ls=ed77ed518a76f1cec49d0006a541a971;store-region=cn-ha;MONITOR_DEVICE_ID=ca0683ad-99ca-40a3-8a1c-1b2b4a77dd2d;csrf_session_id=c9d1390ecd03a771cdc40ec25c0b7635;gf_part_609296=71;odin_tt=7025ac9b032965877dbb3d72b5782ad4d61d4555b80de7d4ef45ecac767ef39fe9b46c7c336251d827f5aae95d89bc1b1146f79c9722890cb2b1ba46ca88ef01;MONITOR_WEB_ID=6805304a-2640-4100-81c9-448a90cffa42;passport_csrf_token_default=6140549ed5579349981f980cb32d1506;passport_csrf_token=6140549ed5579349981f980cb32d1506;uid_tt_ss_ls=23506bfda2d9c8012114682f8f6d9c00;uid_tt_ls=23506bfda2d9c8012114682f8f6d9c00;sid_ucp_v1_ls=1.0.0-KGM4ODM3OGI0ZDllNTlkZmUzOGRiNjg1NGE3YzU0ODU0YWQ4NDdjNGUKGgidgNCXi42LBxCmlY2jBhjRwRIgDDgCQPEHGgJobCIgZWQ3N2VkNTE4YTc2ZjFjZWM0OWQwMDA2YTU0MWE5NzE;ssid_ucp_v1_ls=1.0.0-KGM4ODM3OGI0ZDllNTlkZmUzOGRiNjg1NGE3YzU0ODU0YWQ4NDdjNGUKGgidgNCXi42LBxCmlY2jBhjRwRIgDDgCQPEHGgJobCIgZWQ3N2VkNTE4YTc2ZjFjZWM0OWQwMDA2YTU0MWE5NzE;ttwid=1|DVZQeB6fpxImFBs1QRBAFfbJkFUbr5I7nvsJiV_O8aE|1684228774|426d9954e1b7c4ab5d624703ca72efcf6705f98579b38b31a17353ba07c7dc10;';

    }
    // 查询预约管理
    public function getFulfilmentOrder($data = [])
    {
        //预约单
        $method = '/life/fulfilment/v1/search/travel_agency_order?';

        !isset($data['status']) and $data['status'] = 1;
        !isset($data['trade_type']) and $data['trade_type'] = 99;
        !isset($data['page_index']) and $data['page_index'] = 1;
        !isset($data['page_size']) and $data['page_size'] = 100;

        $data['root_life_account_id'] = '7198386407902021689';

        $res = http_build_query($data);

        $url = $this->baseUrl . $method . $res;

        $response = $this->client->request('GET', $url, [
            'verify' => false,
            'headers' => $this->getHeaders()
        ]);

        $str = $response->getBody()->getContents(); //获取响应内容

        $arr = json_decode($str, true);
        var_dump($arr);
        if ($arr['BaseResp']['StatusCode'] != 0) {
            return [];
        }

        return [
            'data' => $arr['data']['list'],
            'page' => $arr['data']['pagination'],
        ];
    }
    //查询售卖明细
    public function getSellOrder($data = [])
    {

        //status：不传为全部 1：未核销  2：已核销 3申请退款 4 已退款 5 部分核销
        //start_time end_time
        //售卖明细
        $method = '/life/fulfilment/v1/query/certificate_list?';

        !isset($data['trade_type']) and $data['trade_type'] = 99;
        !isset($data['page_index']) and $data['page_index'] = 1;
        !isset($data['page_size']) and $data['page_size'] = 50; //奇怪的设定，读取条数大于50不返回用户信息

        $data['root_life_account_id'] = '7198386407902021689';

        $query = [
            // 'start_time' => $data['start_time'],
            // 'end_time' => $data['end_time'],
            'page_index' => $data['page_index'],
            'page_size' => $data['page_size'],
            'root_life_account_id' => $data['root_life_account_id']
        ];
        $res = http_build_query($query);
        $url = $this->baseUrl . $method . $res;
     

        $body = [
            'filter' => [
                // 'start_time' => $data['start_time'],
                // 'end_time' => $data['end_time'],
                // 'order_id' => isset($data['order_id']) ? $data['order_id'] : '',
                'start_time' => isset($data['start_time']) ? $data['start_time'] : '',
                'end_time' => isset($data['end_time']) ? $data['end_time'] : '',
                // 'status' => $data['status'],
            ]
        ];
        if(isset($data['order_id'])) {
            $body['filter']['order_id'] = $data['order_id'];
        }
        
        $requestData = [
            'verify' => false,
            'headers' => $this->getHeaders(),
            // 'query' => $query,
            'body' => json_encode($body)
        ];
        //自己拼接的url end_time=1679673599  
        //https://life.douyin.com/life/fulfilment/v1/query/certificate_list?page_index=1&page_size=1&root_life_account_id=7198386407902021689
        //正常的链接
        // $url = 'https://life.douyin.com/life/fulfilment/v1/query/certificate_list?end_time=1679673599&page_index=1&page_size=20&start_time=1679068800&root_life_account_id=7198386407902021689';
        // dump($url);
        // dump($requestData);
        // exit;
        $response = $this->client->request('POST', $url, $requestData);

        $str = $response->getBody()->getContents(); //获取响应内容
        
        $arr = json_decode($str, true);

        if ($arr['BaseResp']['StatusCode'] != 0) {
            //------------------------------这是调用读取失败，需要有预警处理---------------------------
            return [
                'data' => [],
                'page' => $arr['data']['pagination'],
                'code' => -1
            ];
        }
        //如果没有读取到的数据返回空
        if (empty($arr['data']['list'])) {
            return [
                'data' => [],
                'page' => $arr['data']['pagination'],
                'code' => 200
            ];
        }

        return [
            'data' => $arr['data']['list'],
            'page' => $arr['data']['pagination'],
            'code' => 200
        ];
    }

    //创建预约单
    public function createOrder($data)
    {
        $method = '/life/fulfilment/v1/create/multi_day_tour_book/?';
        $data['root_life_account_id'] = '7198386407902021689';
        // $res = http_build_query($data);
        $res = http_build_query(['root_life_account_id' => '7198386407902021689' ]);
        $url = $this->baseUrl . $method . $res;
        // $data['OrderId'] = '8000007731661446658';
        //先从待预约订单接口中查出这条单子的信息
        $order = $this->getFulfilmentOrder([
            'status' => 1,
            'order_id' => $data['OrderId'],
            'page_size' => 100,
        ]);
        // dump($order);
        if (empty($order['data']) and empty($order['data'][0]['UserId'])) {
            return [
                'data' => [],
                'page' => [],
                'code' => -1
            ];
        }
        $body = [
            'OrderId' => $data['OrderId'],
            'Uid' => $order['data'][0]['UserId'],
            'BookInfo' => [
                'PreSaleSkuId' => $data['PreSaleSkuId'],
                'PlayStartDate' => date("Y-m-d",strtotime($data['PlayStartDate'])),
                'PlayEndDate' => date("Y-m-d",strtotime($data['PlayEndDate'])),
                'ContractUser' => [
                    'Name' => $data['Name'],
                    'Phone' => $data['Phone'],
                ],
                'Notice' => empty($data['Notice']) ? '' : $data['Notice'],
            ]
        ];
        $body = json_encode($body);
      
        $requestData = [
            'verify' => false,
            'headers' => $this->getHeaders(),
            'body' => $body
        ];
        $response = $this->client->request('POST', $url, $requestData);
        $str = $response->getBody()->getContents(); //获取响应内容
        $arr = json_decode($str, true);
        if ($arr['status_code'] == 0 and $arr['BaseResp']['StatusCode'] == 0) {
            return [
                'data' => [],
                'page' => [],
                'code' => 200
            ];
        } else {
            return [
                'data' => [],
                'page' => [],
                'code' => -1
            ];
        }

    }
    //获取售卖商品的信息
    public function getSellGoods()
    {
        //售卖明细
        $method = '/life/goods/product/list/v2?';

        $data['ac_app'] = '10148';
        $data['root_life_account_id'] = '7198386407902021689';

        $res = http_build_query($data);

        $url = $this->baseUrl . $method . $res;
        //---------------------------做参数处理---------------------------
        $body = '{"exclude_poi_info":true,"product_type_list":["1","11","12","15","19"],"filter_status":9,"cursor":"0","count":50,"search_after":"","search_param_str":"{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}","permission_common_param":{"all_selected_params":"{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}"}}';

        $requestData = [
            'verify' => false,
            'headers' => $this->getHeaders(),
            'body' => $body
        ];

        $response = $this->client->request('POST', $url, $requestData);
        $str = $response->getBody()->getContents(); //获取响应内容
        $arr = json_decode($str, true);

        if ($arr['BaseResp']['StatusCode'] != 0) {
            //------------------------------这是调用读取失败，需要有预警处理---------------------------
            return [
                'data' => [],
                'page' => $arr['data']['pagination'],
                'code' => -1
            ];
        }
        //如果没有读取到的数据返回空
        if (empty($arr['product_detail_list'])) {
            return [
                'data' => [],
                // 'page' => $arr['data']['pagination'],
                'code' => 200
            ];
        }

        return [
            'data' => $arr['product_detail_list'],
            // 'page' => $arr['data']['pagination'],
            'code' => 200
        ];


    }
    //查询订单详情
    // public function getOrderDetail()
    // {
    //     //status：不传为全部 1：未核销  2：已核销 3申请退款 4 已退款 5 部分核销
    //     //start_time end_time
    //     //售卖明细
    //     $method = '/life/fulfilment/v1/query/certificate_list?';

    //     !isset($data['status']) and $data['status'] = 1;
    //     !isset($data['trade_type']) and $data['trade_type'] = 99;
    //     !isset($data['page_index']) and $data['page_index'] = 1;
    //     !isset($data['page_size']) and $data['page_size'] = 100;

    //     $data['root_life_account_id'] = '7198386407902021689';

    //     $res = http_build_query($data);


    //     $url = $this->baseUrl . $method . $res;
    //     $body = [
    //         'filter' => [
    //             'start_time' => $data['start_time'],
    //             'end_time' => $data['end_time'],
    //             'status' => $data['status'],
    //         ]
    //     ];


    //     $response = $this->client->request('POST', $url, [
    //         'verify' => false,
    //         'headers' => $this->getHeaders(),
    //         'body' => json_encode($body)
    //     ]);

    //     $str = $response->getBody()->getContents(); //获取响应内容
    //     $arr = json_decode($str, true);
    //     if ($arr['BaseResp']['StatusCode'] != 0) {
    //         return [];
    //     }

    //     return [
    //         'data' => $arr['data']['list'],
    //         'page' => $arr['data']['pagination'],
    //     ];

    // }
    protected function getHeaders()
    {
        return [
            'Cookie' => $this->cookie,
            'User-Agent' => 'Apifox/1.0.0 (https://www.apifox.cn)',
            'Content-Type' => 'application/json',
            'Accept' => '*/*',
            'Host' => 'life.douyin.com',
            'Connection' => 'keep-alive',
        ];
    }


}